package quq.missq.activity;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.google.gson.Gson;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;

import quq.missq.BaseActivity;
import quq.missq.Constants;
import quq.missq.R;
import quq.missq.beans.BaseBean;
import quq.missq.beans.MyInformationBean;
import quq.missq.beans.School;
import quq.missq.utils.AstroUtils;
import quq.missq.utils.BItmapUploadAsyncTask;
import quq.missq.utils.BitmapUtils;
import quq.missq.utils.HttpBItmapRequest;
import quq.missq.utils.ImageUtil;
import quq.missq.utils.UserTools;
import quq.missq.utils.VolleyTool;
import quq.missq.views.SelectSexDialog;
import quq.missq.views.SelectTallDialog;
import quq.missq.views.SelectTimeDialog;

/**
 * Created by Administrator on 2015/9/17.
 */
public class PersonalInfoActivity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout rl_headimage;
    private RelativeLayout rl_nickname;
    private RelativeLayout rl_account_id;
    private RelativeLayout rl_account_name;
    private RelativeLayout rl_account_sex;
    private RelativeLayout rl_account_tall;
    private RelativeLayout rl_account_brith;
    private RelativeLayout rl_account_star;
    private RelativeLayout rl_account_school;
    private RelativeLayout rl_account_goschool;
    private RelativeLayout rl_account_pen;
    private RelativeLayout rl_account_bg;
    private Intent intent;
    private TextView tv_nickname;
    private TextView tv_account_name;
    private TextView tv_pen;
    private ImageView iv_back;
    private ImageView iv_headimage;
    private ImageView imvBg;
    private TextView tv_account_school;
    private TextView tv_account_star;
    private TextView tv_account_goschool;
    private TextView tvId;

    private DatePickerDialog mDatePickerDialog;
    private String mHeadPath;
    private String mBgPath;
    private TextView tv_account_brith;
    private TextView tv_account_tall;
    private SelectTallDialog selectTallDialog;
    private SelectTimeDialog selectTimeDialog;
    private TextView tv_account_sex;
    private SelectSexDialog selectSexDialog;
    private MyInformationBean bean;
    private HashMap<String, String> params;
    private Bitmap bmpHead;
    private Bitmap bmpBg;
    private int birthdayPrivacy;
    private int heightPrivacy;
    private int namePrivacy;
    private int gender;
    private int mSchoolId;
    private ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.personal_information);
        initView();
        initData();
        initListener();
    }

    private void initData() {
        bean = (MyInformationBean) getIntent().getSerializableExtra("info");
        if (bean != null) {
            tv_nickname.setText(bean.getData().getNkname());
            if (bean.getData().getGender() == 1) {
                tv_account_sex.setText("男");
            } else {
                tv_account_sex.setText("女");
            }
            tvId.setText("" + bean.getData().getId());
            tv_account_name.setText(bean.getData().getName());
            tv_account_school.setText(bean.getData().getSchoolName());
            tv_account_star.setText(bean.getData().getAstro());
            tv_account_tall.setText(bean.getData().getHeight() + "厘米");
            tv_account_brith.setText(bean.getData().getBirthday());
            tv_account_goschool.setText(bean.getData().getEnroll() + "年");
            tv_pen.setText(bean.getData().getSignature());
            if (bean.getData().getAvatar80() != null || !bean.getData().getAvatar80().isEmpty()) {

                VolleyTool.getImageLoader().get(Constants.IMAGE_HOST + bean.getData().getAvatar80(), new ImageLoader.ImageListener() {
                    @Override
                    public void onResponse(ImageLoader.ImageContainer imageContainer, boolean b) {
                        if (imageContainer != null && imageContainer.getBitmap() != null) {
                            iv_headimage.setImageBitmap(BitmapUtils.toRoundBitmap(imageContainer.getBitmap(), 0, 0));
                        } else {
                            iv_headimage.setImageBitmap(BitmapUtils.toRoundBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.default_empty2), 0, 0));
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        iv_headimage.setImageBitmap(BitmapUtils.toRoundBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.default_empty2), 0, 0));
                    }
                });
            } else {
                iv_headimage.setImageBitmap(BitmapUtils.toRoundBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.default_empty2), 0, 0));

            }
            if (bean.getData().getBackground() != null || !bean.getData().getBackground().isEmpty()) {
                VolleyTool.getImageLoader().get(Constants.IMAGE_HOST + bean.getData().getBackground(), new ImageLoader.ImageListener() {
                    @Override
                    public void onResponse(ImageLoader.ImageContainer imageContainer, boolean b) {
                        if (imageContainer != null && imageContainer.getBitmap() != null) {
                            imvBg.setImageBitmap(imageContainer.getBitmap());
                        } else {
                            imvBg.setImageDrawable(getResources().getDrawable(R.mipmap.default_empty2));
                        }


                    }

                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        imvBg.setImageDrawable(getResources().getDrawable(R.mipmap.default_empty2));

                    }
                });
            } else {
                imvBg.setImageDrawable(getResources().getDrawable(R.mipmap.default_empty2));
            }


        }
    }

    private void initListener() {
        rl_headimage.setOnClickListener(this);
        rl_nickname.setOnClickListener(this);
        rl_account_id.setOnClickListener(this);
        rl_account_name.setOnClickListener(this);
        rl_account_sex.setOnClickListener(this);
        rl_account_tall.setOnClickListener(this);
        rl_account_brith.setOnClickListener(this);
        rl_account_star.setOnClickListener(this);
        rl_account_school.setOnClickListener(this);
        rl_account_goschool.setOnClickListener(this);
        rl_account_pen.setOnClickListener(this);
        rl_account_bg.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        findViewById(R.id.iv_submit).setOnClickListener(this);
    }

    private void initView() {
        iv_back = (ImageView) findViewById(R.id.iv_back);
        imvBg = (ImageView) findViewById(R.id.imv_bg);

        rl_headimage = (RelativeLayout) findViewById(R.id.rl_headimage);
        rl_nickname = (RelativeLayout) findViewById(R.id.rl_nickname);
        rl_account_id = (RelativeLayout) findViewById(R.id.rl_account_id);
        rl_account_name = (RelativeLayout) findViewById(R.id.rl_account_name);
        rl_account_sex = (RelativeLayout) findViewById(R.id.rl_account_sex);
        rl_account_tall = (RelativeLayout) findViewById(R.id.rl_account_tall);
        rl_account_brith = (RelativeLayout) findViewById(R.id.rl_account_brith);
        rl_account_star = (RelativeLayout) findViewById(R.id.rl_account_star);
        rl_account_school = (RelativeLayout) findViewById(R.id.rl_account_school);
        rl_account_goschool = (RelativeLayout) findViewById(R.id.rl_account_goschool);
        rl_account_pen = (RelativeLayout) findViewById(R.id.rl_account_pen);
        rl_account_bg = (RelativeLayout) findViewById(R.id.rl_account_bg);

        tv_nickname = (TextView) findViewById(R.id.tv_nickname);
        tv_account_name = (TextView) findViewById(R.id.tv_account_name);
        tv_pen = (TextView) findViewById(R.id.tv_pen);
        iv_headimage = (ImageView) findViewById(R.id.iv_headimage);
        tv_account_school = (TextView) findViewById(R.id.tv_account_school);
        tv_account_brith = (TextView) findViewById(R.id.tv_account_brith);
        tv_account_tall = (TextView) findViewById(R.id.tv_account_tall);
        tv_account_sex = (TextView) findViewById(R.id.tv_account_sex);

        tv_account_star = (TextView) findViewById(R.id.tv_account_star);
        tv_account_goschool = (TextView) findViewById(R.id.tv_account_goschool);
        tvId = (TextView) findViewById(R.id.tv_id);

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            HashMap<String, Bitmap> bitmapHashMap = new HashMap<>();
            HashMap<String, String> mPaths = new HashMap<>();
            if (mHeadPath != null && !mHeadPath.isEmpty()) {
                bitmapHashMap.put("file", ImageUtil.readFile(mHeadPath));
                mPaths.put("file", mHeadPath);
            }
            if (bmpBg != null) {
                bitmapHashMap.put("bkg", bmpBg);
                mPaths.put("bkg", mBgPath);

            }
            dialog = ProgressDialog.show(PersonalInfoActivity.this, "提示", "正在更新用户信息，请稍候");
            BItmapUploadAsyncTask asyncTask = new BItmapUploadAsyncTask(params, bitmapHashMap, mPaths, Constants.UPDATE_USER_INFO, new HttpBItmapRequest.HttpRequestListener() {
                @Override
                public void httpError() {
                    dialog.dismiss();
                    showToast("用户信息更新失败请稍候再试");
                }

                @Override
                public void httpSuccess(String msg) {
                    dialog.dismiss();
                    //Log.i("msg+++++++++++", msg);
                    Gson gson = new Gson();
                    BaseBean bb = gson.fromJson(msg, BaseBean.class);
                    if (bb.getCode() < 0) {
                        showToast(bb.getMessage());
                        return;
                    }
                    MyInformationBean b = gson.fromJson(msg, MyInformationBean.class);

                    Intent intent = new Intent();
                    intent.putExtra("info", b);

                    setResult(RESULT_OK, intent);
                    finish();

                }
            });
            asyncTask.execute();


        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) switch (requestCode) {
            case 0:
                String name1 = data.getExtras().getString("Name");
                tv_nickname.setText(name1);
                break;
            case 1:
                String name2 = data.getExtras().getString("Name");
                tv_account_name.setText(name2);
                namePrivacy = data.getIntExtra("namePrivacy", 1);
                Log.i("wcx",namePrivacy+"namePrivacy");
                break;
            case 2:
                String name3 = data.getExtras().getString("pen_Name");
                tv_pen.setText(name3);
                break;
            case 3:
                mHeadPath = data.getStringExtra(SelectPicActivity.KEY_PHOTO_PATH);
                iv_headimage.setImageBitmap(BitmapUtils.toRoundBitmap(ImageUtil.readFile(mHeadPath), 3, R.color.white));
                break;
            case 4:
                Bundle bundle = data.getExtras();
                School school = (School) bundle.getSerializable("school");
                tv_account_school.setText(school.getM_nUniversity_Name());
                mSchoolId = school.getM_nUniversity_ID();
                break;
            case 5:
                mBgPath = data.getStringExtra(SelectPicActivity.KEY_PHOTO_PATH);
                imvBg.setImageBitmap(ImageUtil.readFile(mBgPath));
                break;
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_account_sex://选择性别
                selectSexDialog = new SelectSexDialog(this);
                selectSexDialog.show();
                selectSexDialog.setSexButtonListener(new SelectSexDialog.SexButtonListener() {
                    @Override
                    public void onPositiveButton(SelectSexDialog dialog) {
                        String sex = dialog.getSex();
                        tv_account_sex.setText(sex);
                        selectSexDialog.dismiss();
                    }
                    @Override
                    public void onNegativeButton(SelectSexDialog dialog) {
                        selectSexDialog.dismiss();
                    }
                });
                break;
            case R.id.rl_account_tall://选择身高
                selectTallDialog = new SelectTallDialog(this);
                selectTallDialog.show();
                selectTallDialog.setTallButtonListener(new SelectTallDialog.TallButtonListener() {
                    @Override
                    public void onPositiveButton(SelectTallDialog dialog) {
                        String tallHeight = dialog.getTallHeight();
                        tv_account_tall.setText(tallHeight);
                        selectTallDialog.dismiss();
                    }

                    @Override
                    public void onNegativeButton(SelectTallDialog dialog) {
                        selectTallDialog.dismiss();
                    }
                });
                break;
            case R.id.rl_account_goschool://选择入学时间
                selectTimeDialog = new SelectTimeDialog(this);
                selectTimeDialog.show();
                selectTimeDialog.setTimeButtonListener(new SelectTimeDialog.TimeButtonListener() {
                    @Override
                    public void onPositiveButton(SelectTimeDialog dialog) {
                        String time = dialog.getTime();
                        tv_account_goschool.setText(time);
                        selectTimeDialog.dismiss();
                    }

                    @Override
                    public void onNegativeButton(SelectTimeDialog dialog) {
                        selectTimeDialog.dismiss();
                    }
                });
                break;
            case R.id.rl_headimage://头像
                intent = new Intent(this, SelectPicActivity.class);
                intent.putExtra(SelectPicActivity.KEY_CUT_X,1);
                intent.putExtra(SelectPicActivity.KEY_CUT_Y,1);
                startActivityForResult(intent, 3);
                break;
            case R.id.rl_account_bg:
                intent = new Intent(this, SelectPicActivity.class);
                intent.putExtra(SelectPicActivity.KEY_CUT_X,1);
                intent.putExtra(SelectPicActivity.KEY_CUT_Y,1);
                startActivityForResult(intent, 5);
                break;
            case R.id.rl_account_school://选择学校
                intent = new Intent(this, SchoolChooseActivity.class);
                startActivityForResult(intent, 4);
                break;
            case R.id.rl_account_brith://选择生日
                mDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        tv_account_brith.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                        //改变星座
                        tv_account_star.setText(AstroUtils.star((monthOfYear + 1), dayOfMonth));
                    }
                }, 1990, 1, 1);
                mDatePickerDialog.show();
                break;
            case R.id.rl_nickname://修改昵称
                intent = new Intent();
                intent.setClass(this, ModifyInfoActivity.class);
                intent.putExtra("type", 0);
                startActivityForResult(intent, 0);
                break;
            case R.id.rl_account_name://修改姓名
                intent = new Intent();
                intent.setClass(this, ModifyInfoActivity.class);
                intent.putExtra("type", 1);
                startActivityForResult(intent, 1);
                break;
            case R.id.rl_account_pen://修改个性签名
                intent = new Intent();
                intent.setClass(this, ModifyInfoActivity.class);
                intent.putExtra("type", 2);
                startActivityForResult(intent, 2);
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_submit:
                params = new HashMap<>();
                String nkName = tv_nickname.getText().toString();
                String birthday = tv_account_brith.getText().toString();
                String schoolName = tv_account_school.getText().toString();
                if (nkName == null || nkName.isEmpty()) {
                    showToast("昵称必须要有呦");
                    return;
                }
                if (birthday == null || birthday.isEmpty()) {
                    showToast("请输入您的生日");
                    return;
                }
                if (schoolName == null || schoolName.isEmpty()) {
                    showToast("学校不能为空");
                    return;
                }
                ///////////////////////////////////////////
                params.put("nkname", nkName);
                if ("男".equals("" + tv_account_sex.getText()))
                    params.put("gender", "" + 1);
                else
                    params.put("gender", "" + 2);
                params.put("signature", "" + tv_pen.getText().toString());
                params.put("name", tv_nickname.getText().toString() + "");
                params.put("namePrivacy", "" + namePrivacy);
                params.put("height", (tv_account_tall.getText().toString()).replaceAll("厘米", " "));
                params.put("heightPrivacy", "" + heightPrivacy);
                params.put("birthday", "" + tv_account_brith.getText().toString());
                params.put("birthdayPrivacy", "" + birthdayPrivacy);
                params.put("astro", "" + tv_account_star.getText().toString());
                params.put("schoolName", tv_account_school.getText().toString() + "");
                params.put("enroll", (tv_account_goschool.getText().toString() + "").replaceAll("年", ""));
                params.put("schoolId", "" + mSchoolId);
                params.put("acc_token", UserTools.getUser(this).getAcc_token() + "");

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (mBgPath != null) {
                            Bitmap bmp = ImageUtil.readFile(mBgPath);

                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inSampleSize = 1;
                            bmpBg = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length, options);
                            bmpBg = BitmapUtils.blurBitmap(bmpBg, 18f, PersonalInfoActivity.this);

                        }
                        handler.sendEmptyMessage(0);
                    }
                }).start();
                break;
        }
    }
}
